﻿#region Header
/*
 * name：Unity
 * author：Kain
 * date：11/25/2010 4:05:00 PM
 *********************************************
 * History:
 * $Header$
 * $History$
 */
#endregion

#region imported namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Web;
using Cherry.Agile.Json;
#endregion

namespace Cherry.Agile
{
    static class Unity
    {
        public const string NAMESPACE = "http://www.cherry.cn/agile";

        public static string DataTableToJsonString(System.Data.DataTable dt)
        {
            JsonData json = new JsonData();
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                JsonData drJson = new JsonData();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    JsonData drJson1 = new JsonData();
                    drJson1 = dr[i].ToString();
                    drJson.Add(drJson1);
                }
                json.Add(drJson);
            }
            return json.ToJson();
        }

        public static string GetFileMd5(string file)
        {

            using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] buff = md5.ComputeHash(stream);
                string resule = System.BitConverter.ToString(buff);
                resule = resule.Replace("-", "");
                return resule;
            }
        }

        static string GetASPNET20machinekey()
        {
            StringBuilder aspnet20machinekey = new StringBuilder();
            string key64byte = GetRandomKey(64);
            string key32byte = GetRandomKey(32);
            aspnet20machinekey.Append("<machineKey \n");
            aspnet20machinekey.Append("validationKey=\"" + key64byte + "\"\n");
            aspnet20machinekey.Append("decryptionKey=\"" + key32byte + "\"\n");
            aspnet20machinekey.Append("validation=\"SHA1\" decryption=\"AES\"\n");
            aspnet20machinekey.Append("/>\n");
            return aspnet20machinekey.ToString();
        }

        static string GetRandomKey(int bytelength)
        {
            byte[] buff = new byte[bytelength];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(buff);
            StringBuilder sb = new StringBuilder(bytelength * 2);
            for (int i = 0; i < buff.Length; i++)
                sb.Append(string.Format("{0:X2}", buff[i]));
            return sb.ToString();
        }


    }
}
